export const REG_ID =
  /^[1-8][1-7]\d{4}(?:19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dX]$/;

export const REG_PHONE = /^1[34578]\d{9}$/g;
export const checkID = (val: string) => {
  return REG_ID.test(val);
};

export const getGenderByID = (val: string) => {
  const genderVal = val.charAt(16);

  if (genderVal !== undefined) {
    if (parseInt(genderVal, 10) % 2 === 0) {
      return '女';
    }
    return '男';
  }
  return '计算错误';
};

export const getBirthdayByID = (val: string) => {
  val = val.substring(6, 14);
  const year = val.substring(0, 4);
  const month = val.substring(4, 6);
  const date = val.substring(6, 8);
  const str = `${year}-${month}-${date}`;
  return str;
};

export const calculateAge = (val: string) => {
  const today = new Date();
  const birthDate = new Date(getBirthdayByID(val));

  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDifference = today.getMonth() - birthDate.getMonth();
  if (
    monthDifference < 0 ||
    (monthDifference === 0 && today.getDate() < birthDate.getDate())
  ) {
    age -= 1;
  }
  return age;
};
